package com.cy.jt.security.config.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 自定义成功请求处理操作
 */
public class RedirectAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    //需要跳转的url
//    private String redirectUrl;
//
//    public RedirectAuthenticationSuccessHandler(String redirectUrl) {
//        this.redirectUrl = redirectUrl;
//    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest,
                                        HttpServletResponse httpServletResponse,
                                        Authentication authentication) throws IOException, ServletException {
//        httpServletResponse.sendRedirect(redirectUrl);
        //获取登录用户的信息
        //获取用户身份(getPrincipal)
        User principal = (User) authentication.getPrincipal();
        System.out.println(principal.getUsername() +
                "/" + principal.getPassword() +
                "/" + principal.getAuthorities());
        //获取用户凭证
        Object credentials = authentication.getCredentials();
        System.out.println("Principal=" + principal);
        System.out.println("credentials=" + credentials);

        //设置数据响应编码
        httpServletResponse.setCharacterEncoding("utf-8");
        httpServletResponse.setContentType("application/json;charset=utf-8");
        PrintWriter out = httpServletResponse.getWriter();
        Map<String, Object> map = new HashMap<>();
        map.put("state", "200");
        map.put("msg", "succeed");
//        out.println("{\"state\":200,\"msg\":\"ok\"}");
        String jsonStr = new ObjectMapper().writeValueAsString(map);
        out.println(jsonStr);
        out.flush();

    }
}
